import {
  Body,
  Controller,
  Param,
  Post,
  Req,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { BookService } from './book.service';
import { AddBookDto } from './dto/add-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import * as path from 'path';
import { storage } from 'src/utils/file';
import { Request } from 'express';

@Controller('book')
export class BookController {
  constructor(private readonly bookService: BookService) {}

  @Post('add')
  add(@Body() book: AddBookDto) {
    return this.bookService.add(book);
  }

  @Post('delete/:id')
  delete(@Param('id') id: string) {
    return this.bookService.delete(id);
  }

  @Post('update')
  update(@Body() book: UpdateBookDto) {
    return this.bookService.update(book);
  }

  @Post('detail/:id')
  detail(@Param('id') id: string) {
    return this.bookService.detail(id);
  }

  @Post('list')
  list(@Body('name') name: string | undefined) {
    return this.bookService.list(name);
  }

  @Post('uploadCover')
  @UseInterceptors(
    FileInterceptor('coverImage', {
      dest: 'uploads',
      storage: storage,
      limits: {
        fileSize: 1024 * 1024 * 5, // 5MB
      },
      fileFilter: (req, file, cb) => {
        const extname = path.extname(file.originalname);
        if (['.png', '.jpg', '.gif', '.jpeg'].includes(extname)) {
          cb(null, true);
        } else {
          cb(new Error('只能上传图片'), false);
        }
      },
    }),
  )
  uploadCover(
    @UploadedFile() file: Express.Multer.File,
    @Req() request: Request,
  ) {
    const serverAddress = `${request.protocol}://${request.get('host')}`;
    const fileUrl = `${serverAddress}/${file.path}`;
    return {
      code: 0,
      message: '上传成功',
      data: {
        url: fileUrl,
      },
    };
  }

  @Post('uploadBook')
  @UseInterceptors(
    FileInterceptor('bookFile', {
      dest: 'uploads',
      storage: storage,
      limits: {
        fileSize: 1024 * 1024 * 10, // 10MB
      },
      fileFilter: (req, file, cb) => {
        const extname = path.extname(file.originalname);
        if (
          ['.txt', '.pdf', '.epub', '.mobi', '.docx', '.doc'].includes(extname)
        ) {
          cb(null, true);
        } else {
          cb(new Error('只能上传文本文档'), false);
        }
      },
    }),
  )
  uploadBook(
    @UploadedFile() file: Express.Multer.File,
    @Req() request: Request,
  ) {
    const serverAddress = `${request.protocol}://${request.get('host')}`;
    const fileUrl = `${serverAddress}/${file.path}`;
    return {
      code: 0,
      message: '上传成功',
      data: {
        url: fileUrl,
      },
    };
  }
}
